package com.wbao.dianniu.ui;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts.Photo;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.data.MobileData;
import com.wbao.dianniu.indexView.CharacterParser;
import com.wbao.dianniu.indexView.ContactsSortAdapter;
import com.wbao.dianniu.indexView.ContactsSortModel;
import com.wbao.dianniu.indexView.PinyinComparatorContact;
import com.wbao.dianniu.indexView.SideBar;
import com.wbao.dianniu.indexView.SideBar.OnTouchingLetterChangedListener;
import com.wbao.dianniu.listener.IMobileCheckListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.MobileCheckManager;
import com.wbao.dianniu.R;

/**
 * 邀请好友加入电纽
 * 
 * @author yejianjun
 *
 */
public class InviteFriendActivity extends BaseActivity implements IMobileCheckListener {
	/** 获取库Phone表字段 **/
    private static final String[] PHONES_PROJECTION = new String[] {
            Phone.DISPLAY_NAME, Phone.NUMBER, Photo.PHOTO_ID, Phone.CONTACT_ID };
    /** 联系人显示名称 **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;
    /** 电话号码 **/
    private static final int PHONES_NUMBER_INDEX = 1;
    /** 头像ID **/
    private static final int PHONES_PHOTO_ID_INDEX = 2;
    /** 联系人的ID **/
    private static final int PHONES_CONTACT_ID_INDEX = 3;
    /**联系人名称**/  
//    private ArrayList<String> mContactsName = new ArrayList<String>();  
//    /**联系人手机号**/  
    private ArrayList<ContactsSortModel> mContactsNumber = new ArrayList<ContactsSortModel>();  
    /**联系人头像**/  
//    private ArrayList<Bitmap> mContactsPhonto = new ArrayList<Bitmap>();  
    
//    private ArrayList<E> mContactsData = new ArrayList
    Context mContext = null;
    MobileCheckManager manager;
    private LinearLayout waittingLayout;
	private ProgressBar waittingProBar;
	private TextView waittingTV;
	
	private SideBar sideBar;
	private TextView dialog;
	private ContactsSortAdapter adapter;
	private ListView sortListView;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private ArrayList<ContactsSortModel> SourceDateList;
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparatorContact pinyinComparator;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentLayout(R.layout.activity_invite,LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
		setTitleName("邀请好友加入电纽");
		mContext = this;
		initWattingView();
		// 异步获取联系人信息
		new Handler().post(new Runnable() {
			
			@Override
			public void run() {
				 /**得到手机通讯录联系人信息**/  
			    getPhoneContacts();
			  //联系人列表发送给服务器 返回列表对应数据
			    reqList();
			}
		});
		initData();
	    initView();
	}
	
	private void initData(){
		//实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparatorContact();
		SourceDateList = new ArrayList<ContactsSortModel>();
		adapter = new ContactsSortAdapter(this, SourceDateList);
		// 根据a-z进行排序源数据
//		Collections.sort(SourceDateList, pinyinComparator);
	}
	
	private void initView(){
		sideBar = (SideBar) findViewById(R.id.sidebar);
		dialog = (TextView) findViewById(R.id.choose_indext_dialog);
		//设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);
				}
			}
		});
		sideBar.setTextView(dialog);
		sortListView = (ListView) findViewById(R.id.invite_list);
		sortListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				
				// 点击发送短信
				String mobile = ((ContactsSortModel)adapter.getItem(position)).getMobile();
				doSendSMSTo(mobile,getResources().getString(R.string.invate_friend_join));
			}
		});
		sortListView.setAdapter(adapter);
		
	}
	
	
	private void initWattingView(){
		waittingLayout = (LinearLayout) findViewById(R.id.waitting_layout);
		waittingProBar = (ProgressBar) findViewById(R.id.waitting_progress);
		waittingTV = (TextView) findViewById(R.id.waitting_text_desc);
	}
	
	private void reqList() {
		manager = new MobileCheckManager(this);
		manager.addMobileCheckListener(this);
		String str = "";
		for (int i = 0; i < mContactsNumber.size(); i++) {
			str = str +  mContactsNumber.get(i).getMobile() + "," ;
		}
		manager.checkMobiles(GlobalContext.accountId, str);
	}

	/**
	 * 调起系统发短信功能
	 * 
	 * @param phoneNumber
	 * @param message
	 */
	public void doSendSMSTo(String phoneNumber, String message) {
		if (PhoneNumberUtils.isGlobalPhoneNumber(phoneNumber)) {
			Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phoneNumber));
			intent.putExtra("sms_body", message);
			startActivity(intent);
		}
	}
	
	  private void getPhoneContacts() {
		  ContentResolver resolver = this.getContentResolver();
	        // 获取手机联系人
	      Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
	      if (phoneCursor != null) {
	    	  while (phoneCursor.moveToNext()) {
	    		  // 得到手机号码
	                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
	                // 当手机号码为空的或者为空字段 跳过当前循环
	                if (TextUtils.isEmpty(phoneNumber))
	                    continue;
	                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
	                // 得到联系人ID
	                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
	                // 得到联系人头像ID
	                Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);
	             // 得到联系人头像Bitamp
	                Bitmap contactPhoto = null;
	              //photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的  
	                if(photoid > 0 ) {  
	                    Uri uri =ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactid);  
	                    InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);  
	                    contactPhoto = BitmapFactory.decodeStream(input);  
	                }else {  
	                    contactPhoto = BitmapFactory.decodeResource(getResources(), R.drawable.default_head_icon);  
	                }  
//	                mContactsName.add(contactName);
//	                mContactsPhonto.add(contactPhoto);  
	                ContactsSortModel mobileData= new ContactsSortModel();
	                mobileData.setMobile(phoneNumber.replace(" ", "").replace("+86", ""));
	                mobileData.setName(contactName);
	                mobileData.setBitmap(contactPhoto);
	                mContactsNumber.add(mobileData);  
	    	  }
	    	  phoneCursor.close();
	      }
	  }

	@Override
	public void onMobileCheckFailure(int errorCode, String errorMsg) {
		waittingLayout.setVisibility(View.VISIBLE);
		waittingProBar.setVisibility(View.GONE);
		waittingTV.setText("加载失败，请稍后再试...");
	}

	@Override
	public void onMobileCheckSuccess(List<MobileData> list) {
		waittingLayout.setVisibility(View.GONE);
		if(null == list){
			return;
		}
		
		SourceDateList = new ArrayList<ContactsSortModel>();
		for (int i = 0; i < mContactsNumber.size(); i++) {
			
			for (int j = 0; j < list.size(); j++) {
				if(mContactsNumber.get(i).getMobile().equals(list.get(j).getMobile())){
					ContactsSortModel sortModel = new ContactsSortModel();
					sortModel.setName(mContactsNumber.get(i).getName());
					// 汉字转换成拼音
					String pinyin = characterParser.getSelling(mContactsNumber.get(i).getName());
					String sortString = pinyin.substring(0, 1).toUpperCase();
					// 正则表达式，判断首字母是否是英文字母
					if (sortString.matches("[A-Z]")) {
						sortModel.setSortLetters(sortString.toUpperCase());
					} else {
						sortModel.setSortLetters("#");
					}
					sortModel.setBitmap(mContactsNumber.get(i).getBitmap());
					sortModel.setMobile(mContactsNumber.get(i).getMobile());
					sortModel.setFlag(list.get(j).getFlag());
					SourceDateList.add(sortModel);
				}
			}
			
		}
		
		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		adapter.updateListView(SourceDateList);
	}
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		}
		public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
		}
}
